/*******************************************************************************************
Copyright (C) 2018 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*******************************************************************************************/

/*global nmr, MessageBox, InputDialog, mainWindow, NMRArithmetic, MnUi*/
/*jslint plusplus: true, indent: 4*/

function stdSplit() {
	"use strict";
	var spec, refIndex, refSpec, diffSpec, resSpecs = [], i, count, ok, arith, doc, tempPages = [], finalStack;
	doc = mainWindow.activeDocument;
	spec = nmr.activeSpectrum();
	if (!spec.isValid()) {
		MessageBox.critical("NMR spectrum is not found");
		return;
	}
	if (spec.specCount < 2) {
		MessageBox.critical("This script is applicable for stacked 1D spectra only");
		return;
	}
	refIndex = InputDialog.getInt("Reference experiment", "Reference experiment (off-resonance) #:", 1, 1, spec.specCount, 1);
	if (refIndex === undefined) {
		return;
	}
	refIndex -= 1;
	refSpec = nmr.extractSpectrumFromArrayedItem(spec, refIndex);
	refSpec.comment += "\nReference Spectrum";
	resSpecs.push(refSpec);

	count = 1;
	arith = new NMRArithmetic();
	for (i = 0; i < spec.specCount; i++) {
		if (i !== refIndex) {
			diffSpec = nmr.extractSpectrumFromArrayedItem(spec, i);
			ok = arith.sub(spec, refIndex, spec, i, diffSpec, 0);
			if (!ok) {
				MessageBox.critical("Subtraction failed");
				return;
			}
			diffSpec.comment += "\nDifference experiment #" + Number(count);
			resSpecs.push(diffSpec);
			count++;
		}
	}
	finalStack = nmr.createArrayedItem(resSpecs, true);
	if (!finalStack.isValid()) {
		MessageBox.critical("Final stack cannot be created");
		return;
	}
	for (i = 0; i < resSpecs.length; i++) {
		tempPages.push(resSpecs[i].page);
	}
	doc.deletePages(tempPages);
	mainWindow.activeWindow().update();
}

if (this.MnUi && MnUi.scripts_nmr) {
	MnUi.scripts_nmr.scripts_nmr_stdsplit = stdSplit;
}

